<script setup lang="ts">
import { reactive, ref, watch } from 'vue'
import type { ImageType } from '@/api/Image.ts'
import { ImageApi } from '@/api/ImageApi.ts'
import { message } from 'ant-design-vue'

const props = defineProps<{
  open: boolean
}>()

const emit = defineEmits<{
  (e: 'update:open', value: boolean): void
  (e: 'success'): void
}>()

const confirmLoading = ref(false)
const form = reactive<{
  type: ImageType | null
  file: File | null
}>({
  type: null,
  file: null,
})

const typeOptions: { label: string; value: ImageType }[] = [
  { label: '轮播图', value: 'CAROUSEL' },
  { label: '验证码', value: 'CAPTCHA' },
]

watch(
  () => props.open,
  (open) => {
    if (!open) {
      confirmLoading.value = false
      form.type = null
      form.file = null
    }
  }
)

const beforeUpload = (file: File) => {
  form.file = file
  return false
}

const handleCancel = () => {
  emit('update:open', false)
}

const handleOk = async () => {
  if (!form.type) {
    message.error('请选择图片类型')
    return
  }
  if (!form.file) {
    message.error('请选择要上传的图片文件')
    return
  }
  try {
    confirmLoading.value = true
    const id = await ImageApi.upload(form.type, form.file)
    if (id) {
      emit('success')
    } else {
      message.error('上传失败')
    }
  } catch (e) {
    console.error(e)
    message.error('上传失败')
  } finally {
    confirmLoading.value = false
  }
}
</script>

<template>
  <a-modal
    :open="open"
    title="上传图片"
    ok-text="上传"
    cancel-text="取消"
    :confirm-loading="confirmLoading"
    @cancel="handleCancel"
    @ok="handleOk"
  >
    <a-form layout="vertical">
      <a-form-item label="图片类型">
        <a-select v-model:value="form.type" placeholder="选择类型" allow-clear>
          <a-select-option v-for="opt in typeOptions" :key="opt.value" :value="opt.value">
            {{ opt.label }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="选择文件">
        <a-upload :before-upload="beforeUpload" :max-count="1" :file-list="form.file ? [ { name: form.file.name, status: 'done', uid: '1' } ] : []">
          <a-button>选择文件</a-button>
        </a-upload>
        <div v-if="form.file" class="mt-2 text-gray-500 text-sm">{{ form.file.name }}</div>
      </a-form-item>
    </a-form>
  </a-modal>
  </template>


